#include "ThreadEnviador.h"
#include "InterfazPeer.h"

ThreadEnviador::ThreadEnviador(InterfazPeer* interfazPeer, Conexion *conexion, Condition *conditionCSalida, queue<string> *colaSalida)
{
	this->conexion = conexion;
	this->conditionCSalida = conditionCSalida;
	this->colaSalida = colaSalida;
	this->interfazPeer = interfazPeer;
}

ThreadEnviador::~ThreadEnviador()
{
}

void* ThreadEnviador::run(){
	bool recibirOk = true;

	cout << " Thread Enviador " << this->interfazPeer->getPeerId() << endl;

	while((!this->getStop()) &&
			(recibirOk)){

		this->conditionCSalida->mutexLock();

		if(this->colaSalida->empty()){
			this->conditionCSalida->wait();
		}

		if(this->getStop()) {
			this->conditionCSalida->mutexUnlock();
			this->interfazPeer->enviarSenialNoActivo();
			return NULL;
		}

		recibirOk = this->conexion->enviar(this->colaSalida->front());
		cout << "Envio " << this->colaSalida->front() << endl;

		colaSalida->pop();

		this->conditionCSalida->mutexUnlock();

	}

	this->interfazPeer->enviarSenialNoActivo();

	return NULL;
}

void ThreadEnviador::stop(){
	this->Thread::stop();
	this->conditionCSalida->signal();
}
